<template>
  <div class="dict-manage-container">
    <el-row :gutter="20">
      <!-- 左侧：字典类型 -->
      <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <el-card class="dict-type-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">字典类型</span>
              <el-button 
                v-permission="'system:dict:add'"
                type="primary" 
                @click="openTypeDialog('add')">
                添加类型
              </el-button>
            </div>
          </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="typeQuery" class="search-form">
        <el-form-item label="字典名称">
          <el-input 
            v-model="typeQuery.dictName" 
            placeholder="请输入字典名称" 
            clearable
            @keyup.enter="getTypeList" />
        </el-form-item>
        <el-form-item label="字典类型">
          <el-input 
            v-model="typeQuery.dictType" 
            placeholder="请输入字典类型" 
            clearable
            @keyup.enter="getTypeList" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTypeList">搜索</el-button>
          <el-button @click="resetTypeQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 字典类型表格 -->
      <el-table 
        :data="typeList" 
        stripe
        highlight-current-row
        @row-click="selectType"
        style="width: 100%">
        <el-table-column prop="dictName" label="字典名称" min-width="120" />
        <el-table-column prop="dictType" label="字典类型" min-width="150" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button 
              link 
              type="primary" 
              @click.stop="selectType(row)">
              字典数据
            </el-button>
            <el-button 
              v-permission="'system:dict:edit'"
              link 
              type="primary" 
              @click.stop="openTypeDialog('edit', row)">
              编辑
            </el-button>
            <el-button 
              v-permission="'system:dict:remove'"
              link 
              type="danger" 
              @click.stop="deleteType(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="typeQuery.pageNum"
            v-model:page-size="typeQuery.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="typeTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="getTypeList"
            @current-change="getTypeList"
            class="pagination" />
        </el-card>
      </el-col>   

      <!-- 右侧：字典数据 -->
      <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <el-card v-if="selectedType" class="dict-data-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">字典数据 - {{ selectedType.dictName }}</span>
              <el-button 
                v-permission="'system:dict:add'"
                type="primary" 
                @click="openDataDialog('add')">
                添加数据
              </el-button>
            </div>
          </template>

      <!-- 字典数据表格 -->
      <el-table :data="dataList" stripe style="width: 100%">
        <el-table-column prop="dictLabel" label="字典标签" width="150" />
        <el-table-column prop="dictValue" label="字典键值" width="150" />
        <el-table-column prop="dictSort" label="排序" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="样式预览" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.listClass" :type="row.listClass">
              {{ row.dictLabel }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-permission="'system:dict:edit'"
              link 
              type="primary" 
              @click="openDataDialog('edit', row)">
              编辑
            </el-button>
            <el-button 
              v-permission="'system:dict:remove'"
              link 
              type="danger" 
              @click="deleteData(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="dataQuery.pageNum"
            v-model:page-size="dataQuery.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="dataTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="getDataList"
            @current-change="getDataList"
            class="pagination" />
        </el-card>
        
        <!-- 未选择提示 -->
        <el-empty 
          v-else 
          description="请先选择左侧字典类型"
          :image-size="200" />
      </el-col>
    </el-row>

    <!-- 字典类型对话框 -->
    <el-dialog 
      v-model="typeDialogVisible" 
      :title="typeDialogMode === 'add' ? '添加字典类型' : '编辑字典类型'"
      width="600px">
      <el-form 
        ref="typeFormRef"
        :model="typeForm" 
        :rules="typeRules"
        label-width="100px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="typeForm.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input 
            v-model="typeForm.dictType" 
            placeholder="请输入字典类型（如：sys_user_sex）"
            :disabled="typeDialogMode === 'edit'" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="typeForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="typeForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="typeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveType">确定</el-button>
      </template>
    </el-dialog>

    <!-- 字典数据对话框 -->
    <el-dialog 
      v-model="dataDialogVisible" 
      :title="dataDialogMode === 'add' ? '添加字典数据' : '编辑字典数据'"
      width="600px">
      <el-form 
        ref="dataFormRef"
        :model="dataForm" 
        :rules="dataRules"
        label-width="100px">
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="dataForm.dictLabel" placeholder="请输入字典标签" />
        </el-form-item>
        <el-form-item label="字典键值" prop="dictValue">
          <el-input v-model="dataForm.dictValue" placeholder="请输入字典键值" />
        </el-form-item>
        <el-form-item label="排序" prop="dictSort">
          <el-input-number v-model="dataForm.dictSort" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回显样式">
          <el-select v-model="dataForm.listClass" placeholder="请选择样式" clearable>
            <el-option label="默认" value="" />
            <el-option label="主要" value="primary" />
            <el-option label="成功" value="success" />
            <el-option label="信息" value="info" />
            <el-option label="警告" value="warning" />
            <el-option label="危险" value="danger" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="dataForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dataDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveData">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { dictTypeApi, dictDataApi } from '@/api/dict'
import { ElMessage, ElMessageBox } from 'element-plus'

// 字典类型相关
const typeList = ref([])
const typeQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  dictName: '',
  dictType: ''
})
const typeTotal = ref(0)
const selectedType = ref(null)

// 字典数据相关
const dataList = ref([])
const dataQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  dictType: '',
  dictLabel: ''
})
const dataTotal = ref(0)

// 对话框相关
const typeDialogVisible = ref(false)
const typeDialogMode = ref('add')
const typeFormRef = ref(null)
const typeForm = reactive({
  id: null,
  dictName: '',
  dictType: '',
  status: 1,
  remark: ''
})

const dataDialogVisible = ref(false)
const dataDialogMode = ref('add')
const dataFormRef = ref(null)
const dataForm = reactive({
  id: null,
  dictType: '',
  dictLabel: '',
  dictValue: '',
  dictSort: 0,
  status: 1,
  listClass: '',
  remark: ''
})

// 表单验证规则
const typeRules = {
  dictName: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
  dictType: [{ required: true, message: '请输入字典类型', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const dataRules = {
  dictLabel: [{ required: true, message: '请输入字典标签', trigger: 'blur' }],
  dictValue: [{ required: true, message: '请输入字典键值', trigger: 'blur' }],
  dictSort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取字典类型列表
const getTypeList = async () => {
  try {
    const res = await dictTypeApi.getPage(typeQuery)
    typeList.value = res.data.records
    typeTotal.value = res.data.total
  } catch (error) {
    ElMessage.error(error.message || '获取字典类型列表失败')
  }
}

// 重置字典类型查询
const resetTypeQuery = () => {
  typeQuery.dictName = ''
  typeQuery.dictType = ''
  typeQuery.pageNum = 1
  getTypeList()
}

// 选择字典类型
const selectType = (type) => {
  selectedType.value = type
  dataQuery.dictType = type.dictType
  dataQuery.pageNum = 1
  getDataList()
}

// 打开字典类型对话框
const openTypeDialog = (mode, item = null) => {
  typeDialogMode.value = mode
  if (mode === 'add') {
    Object.assign(typeForm, {
      id: null,
      dictName: '',
      dictType: '',
      status: 1,
      remark: ''
    })
  } else {
    Object.assign(typeForm, item)
  }
  typeDialogVisible.value = true
}

// 保存字典类型
const saveType = async () => {
  if (!typeFormRef.value) return
  
  await typeFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (typeDialogMode.value === 'add') {
        await dictTypeApi.add(typeForm)
        ElMessage.success('添加成功')
      } else {
        await dictTypeApi.update(typeForm)
        ElMessage.success('更新成功')
      }
      typeDialogVisible.value = false
      getTypeList()
    } catch (error) {
      ElMessage.error(error.message || '操作失败')
    }
  })
}

// 删除字典类型
const deleteType = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该字典类型吗？', '提示', {
      type: 'warning'
    })
    await dictTypeApi.delete(id)
    ElMessage.success('删除成功')
    if (selectedType.value?.id === id) {
      selectedType.value = null
      dataList.value = []
    }
    getTypeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 获取字典数据列表
const getDataList = async () => {
  try {
    const res = await dictDataApi.getPage(dataQuery)
    dataList.value = res.data.records
    dataTotal.value = res.data.total
  } catch (error) {
    ElMessage.error(error.message || '获取字典数据列表失败')
  }
}

// 打开字典数据对话框
const openDataDialog = (mode, item = null) => {
  dataDialogMode.value = mode
  if (mode === 'add') {
    Object.assign(dataForm, {
      id: null,
      dictType: selectedType.value.dictType,
      dictLabel: '',
      dictValue: '',
      dictSort: 0,
      status: 1,
      listClass: '',
      remark: ''
    })
  } else {
    Object.assign(dataForm, item)
  }
  dataDialogVisible.value = true
}

// 保存字典数据
const saveData = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (dataDialogMode.value === 'add') {
        await dictDataApi.add(dataForm)
        ElMessage.success('添加成功')
      } else {
        await dictDataApi.update(dataForm)
        ElMessage.success('更新成功')
      }
      dataDialogVisible.value = false
      getDataList()
    } catch (error) {
      ElMessage.error(error.message || '操作失败')
    }
  })
}

// 删除字典数据
const deleteData = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该字典数据吗？', '提示', {
      type: 'warning'
    })
    await dictDataApi.delete(id)
    ElMessage.success('删除成功')
    getDataList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
  getTypeList()
})
</script>

<style scoped>
.dict-manage-container {
  padding: 20px;
}

.dict-type-card,
.dict-data-card {
  min-height: calc(100vh - 140px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格行高亮样式 */
:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.current-row) {
  background-color: #ecf5ff !important;
}
</style>